import axios from 'axios'
import history from '../history'
let config = {
    baseURL: '/api/',
    transformRequest: [
        function (data) {
            let ret = '';
            for (let it in data) {
                if ( (typeof data[it] === "object") && (data[it] !== null) ) {
                    for (let x in data[it]) {
                        ret += encodeURIComponent(`${it}[${x}]`) + '=' + encodeURIComponent(data[it][x]) + '&'
                    }
                } else {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }    
            }
            return ret
        }
    ],
    transformResponse: [
        function (data) {
            return data
        }
    ],
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    timeout: 10000,
    responseType: 'json'
};

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    if (!config.headers.Authorization) {
        let token = localStorage.getItem('auth_token')
        if (token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
            config.headers.Authorization = `Bearer ${token}`;
        }
    }
    
    return config;
  }, function (error) {
    // 对请求错误做些什么
    console.log(error)
    return Promise.reject(error);
});

axios.interceptors.response.use(
    response => response.data,
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 返回 401 
                // history.push('/login')
            }
        }
        return error
        return Promise.reject(error)
    }
);


export function get(url) {
    return axios.get(url, config)
}

export function post(url, data) {
    return axios.post(url, data, config)
}

export function destroy(url) {
    return axios.delete(url, config)
}

export function put_http(url, data) {
    return axios.put(url, data, config)
}
